from typing import Optional, Dict
from typing_extensions import override

from bs4 import BeautifulSoup

from buondua.models import Album
from buondua.scrappers.base import BaseParser


class AlbumParser(BaseParser):
    '''Извлекает ссылки на альбомы со страницы с тегами или hot'''

    @override
    def check_url(self, url) -> bool:
        return True

    @override
    def save(self, data: Optional[Dict]):
        pass

    @override
    def extract(self) -> Optional[Dict]:
        pages = self.extract_pages()
        albums = [*self.extract_albums()]
        for p in pages[1:]:
            self.document = self.get_document(p)
            albums += self.extract_albums()
        return {
            'albums': albums
        }

    def extract_pages(self):
        '''Возвращает список URL-ов страниц альбома'''
        pagination_list = self.document.find('ul', class_='pagination-list')
        link_tags = pagination_list.find_all('a') if pagination_list else []
        return [
            (self.BASE_URL + page).encode(self.DEFAULT_ENCODING)
            for page in map(
                lambda page: page['href'] if page['href'][0] == '/' else '/hot',
                link_tags
            )
        ]

    def extract_albums(self):
        '''Извлекает URL-ы на альбомы'''
        return [
            (self.BASE_URL + page).encode(self.DEFAULT_ENCODING)
            for page in map(
                lambda album: album.find('a', class_='item-link')['href'],
                self.document.find_all('div', class_='items-row')
            )
        ]
